package com.joymart.product.service;


import com.joymart.common.error.handling.JoymartBusinessException;
import com.joymart.product.repo.StockRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StockService {
    @Autowired
    private StockRepository stockRepository;

    @Transactional
    @CacheEvict(value = "stock", key = "#productId")
    public void increaseStock(String productId, int quantity) {
        int current = stockRepository.selectForUpdate(productId);
        if(current + quantity < 0) {
            throw new JoymartBusinessException("库存不足");
        }
        stockRepository.updateQuantity(productId, current + quantity);
    }

    @Transactional
    @CacheEvict(value = "stock", key = "#productId")
    public void deductStock(String productId, int quantity) {
        int current = stockRepository.selectForUpdate(productId);
        if(current - quantity < 0) {
            throw new JoymartBusinessException("库存不足");
        }
        stockRepository.updateQuantity(productId, current - quantity);
    }


    @Cacheable(value = "stock", key="#productId")
    public int getCurrentStock(String productId) {
       return stockRepository.getCurrentStock(productId);
    }
}
